package com.b2c.erp.controller.shop;

import com.b2c.interfaces.ShopService;
import com.xiaohongshu.fls.opensdk.client.OauthClient;
import com.xiaohongshu.fls.opensdk.entity.BaseResponse;
import com.xiaohongshu.fls.opensdk.entity.oauth.request.GetAccessTokenRequest;
import com.xiaohongshu.fls.opensdk.entity.oauth.response.GetAccessTokenResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

@Controller
public class ShopOauthController {
    @Autowired
    private ShopService shopService;
    Logger log = LoggerFactory.getLogger(ShopOauthController.class);

    /**
     * 小红书店铺授权回调
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/oauth/xhs")
    public String oauthCallBack(Model model, HttpServletRequest request){
        String code = request.getParameter("code");
        log.info("获得code："+code);
        Integer shopId = Integer.parseInt(request.getParameter("state"));
        //查询店铺信息
        var shop = shopService.getShop(shopId);
        String url = "https://ark.xiaohongshu.com/ark/open_api/v3/common_controller";

        //获取token，通过
        GetAccessTokenRequest request1 = new GetAccessTokenRequest();
        request1.setAppId(shop.getAppkey());
        request1.setCode(code);
        request1.setVersion("2.0");
        request1.setMethod("oauth.getAccessToken");
        request1.setTimestamp((System.currentTimeMillis() / 1000)+"");
        com.xiaohongshu.fls.opensdk.util.Utils.addSign(request1,shop.getAppSercet());

        com.xiaohongshu.fls.opensdk.client.OauthClient oauthClient = new OauthClient(url,shop.getAppkey(),"2.0",shop.getAppSercet());
        try {
            BaseResponse<GetAccessTokenResponse> r = oauthClient.execute(request1);
            if(r.success) {
                log.info("获取token成功，"+r.getData().getAccessToken());
                shopService.updateSessionKey(shopId, Long.parseLong(shopId+""), r.getData().getAccessToken());
                return "redirect:/shop/dashboard?shopId="+shopId;
            }else {
                log.error(r.msg);
                return "redirect:/sys_err?msg="+r.msg;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/";
    }
}
